<?php
declare (strict_types=1);

namespace app\controller;

use app\BaseController;
use PhpAmqpLib\Connection\AMQPStreamConnection;
use PhpAmqpLib\Message\AMQPMessage;

class Direct extends BaseController
{
    public function send()
    {
        // 交换机名
        $exchange = 'direct_logs';

        // 建立连接
        $connection = new AMQPStreamConnection('127.0.0.1', '5672', 'guest', 'guest', '/');
        // 获取信道
        $channel = $connection->channel();
        // 声明交换机
        $channel->exchange_declare($exchange, 'direct', false, false, false);

        // 模拟发送error信息内容
        $messageBody = 'error, now time:' . date('h:i:s');
        // 将我们需要的消息标记为持久化 - 通过设置AMQPMessage的参数delivery_mode = AMQPMessage::DELIVERY_MODE_PERSISTENT
        $message = new AMQPMessage($messageBody, [
            'content_type' => 'text/plain',
            'delivery_mode' => AMQPMessage::DELIVERY_MODE_PERSISTENT
        ]);

        // 绑定error路由
        $channel->basic_publish($message, $exchange, 'error');

        // 模拟发送info信息内容
        $messageBody = 'info, now time:' . date('h:i:s');
        // 将我们需要的消息标记为持久化 - 通过设置AMQPMessage的参数delivery_mode = AMQPMessage::DELIVERY_MODE_PERSISTENT
        $message = new AMQPMessage($messageBody, [
            'content_type' => 'text/plain',
            'delivery_mode' => AMQPMessage::DELIVERY_MODE_PERSISTENT
        ]);

        // 绑定info路由
        $channel->basic_publish($message, $exchange, 'info');

        // 模拟发送warning信息内容
        $messageBody = 'warning, now time:' . date('h:i:s');
        // 将我们需要的消息标记为持久化 - 通过设置AMQPMessage的参数delivery_mode = AMQPMessage::DELIVERY_MODE_PERSISTENT
        $message = new AMQPMessage($messageBody, [
            'content_type' => 'text/plain',
            'delivery_mode' => AMQPMessage::DELIVERY_MODE_PERSISTENT
        ]);

        // 绑定info路由
        $channel->basic_publish($message, $exchange, 'warning');

        // 关闭信道
        $channel->close();
        // 关闭连接
        $connection->close();
        return 'send success';
    }
}
